<template>
  <div class="announcement-editor">
    <table-title
        title="新增随访记录"
        button-mode="back"
        :back-path="'/admin/visit-record'"
        icon="el-icon-s-order">
    </table-title>

    <!-- form -->
    <div class="form-content">
      <el-form ref="form" :model="form" :rules="formRules" label-width="100px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="服务名称" prop="visitName" key="visitName">
              <el-input v-model="form.visitName" placeholder="请输入服务名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-row>
              <el-col :span="19">
                <el-form-item label="居民" style="cursor: pointer">
                  <el-input v-model="personName" placeholder="请选择居民" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5" style="display: flex; justify-content: flex-end; align-items: center;">
                <el-button type="success" @click="choosePerson">选择居民</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="服务状态">
              <el-select v-model="form.status" placeholder="请选择服务状态">
                <el-option label="未完成" value="0"></el-option>
                <el-option label="已完成" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="完成时间">
            <el-date-picker
                v-model="form.time"
                type="datetime"
                placeholder="请选择完成时间"
                prop="time">
            </el-date-picker>
          </el-form-item>
        </el-row>

        <el-row class="action-button">
          <el-col :span="14" align="right">
            <el-button type="danger" icon="el-icon-close" @click="back">取消</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="confirm">
              {{ editID == -1 ? '新增' : '保存' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 选择 -->
    <transfer ref="transfer" id-key="userId" label-key="tuserName" :num="1"></transfer>
  </div>
</template>

<script>
import TableTitle from "../../../components/TableTitle";
import Transfer from "../../../components/Transfer";
import modelUser from "../../../models/user";

export default {
  name: 'VisitRecordEditor',
  components: {Transfer, TableTitle},
  data() {
    return {
      // 正在编辑的
      editID: -1,

      // 数据
      form: {
        /*"comment": "string",
        "servicePeople": 0,
        "status": "string",
        "time": "2021-04-24T09:55:31.793Z",
        "userId": 0,
        "visitId": 0,
        "visitName": "string"*/
        status: "0"
      },
      personName: '',

      // 校验规则
      formRules: {
        visitName: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 100, message: '标题长度在1到100个字符', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    // 获取参数
    this.editID = this.$route.params.id || -1;

    // 编辑信息，获取信息
    if (this.editID != -1) this.getData();
  },
  methods: {
    /**
     * 获取信息
     */
    getData() {
      this.axios.get(this.$store.state.api + '/visit/getById?visitid=' + this.editID)
          .then((response) => {
            if (response.data.code == 200) {
              const data = response.data.data;
              // 无数据
              if (data == null) {
                this.$message({
                  type: 'error',
                  message: '加载数据失败！',
                  onClose: () => {
                    this.$router.replace('/admin/visit-record');
                  }
                });
              }
              else {
                this.form = data;

                this.axios.get(this.$store.state.api + '/user/getById?userid=' + data.userId)
                    .then((response) => {
                      if (response.data.code == 200) {
                        const data = response.data.data;
                        if (data) {
                          this.personName = data.tuserName;
                        }
                      }
                    })
                    .catch((error) => {
                      console.log(error);
                    });
              }
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },

    /**
     * 选人
     */
    choosePerson() {
      modelUser.getUserDataByRole("0")
          .then((data) => {
            if (data.length) {
              // 打开选择
              this.$refs['transfer'].transform(data, this.form.userId ? [this.form.userId] : []).then((chose) => {
                data.forEach((item) => {
                  // 储存姓名
                  if (item.userId == chose[0]) {
                    this.form.userId = item.userId;
                    this.personName = item.tuserName;
                  }
                });
              });
            }
          });
    },

    /**
     * 返回
     */
    back() {
      this.$router.replace('/admin/visit-record');
    },

    /**
     * 保存
     */
    confirm() {
      // 新增
      if (this.editID == -1) {
        this.axios.post(this.$store.state.api + '/visit/add', {
          visitName: this.form.visitName || '',
          status: this.form.status || '',
          time: new Date().format("yyyy-MM-ddThh:mm:ss.SZ"),
          servicePeople: this.$store.state.userData.userId,
          userId: this.form.userId
        }).then((response) => {
          this.$message({
            type: response.data.data ? 'success' : 'error',
            message: response.data.data ? '添加成功！' : '添加失败！',
            duration: 1000,
            onClose: () => {
              this.back();
            }
          });
        }).catch((error) => {
          console.log(error);
        });
      }
      // 更新
      else {
        this.axios.put(this.$store.state.api + '/visit/update', [{
          visitName: this.form.visitName || '',
          status: this.form.status || '',
          time: new Date().format("yyyy-MM-ddThh:mm:ss.SZ"),
          userId: this.form.userId,
          visitId: this.editID
        }]).then((response) => {
          this.$message({
            type: response.data.data ? 'success' : 'error',
            message: response.data.data ? '修改成功！' : '修改失败！',
            duration: 1000,
            onClose: () => {
              this.back();
            }
          });
        }).catch((error) => {
          console.log(error);
        });
      }
    },
  }
};
</script>

<style lang="less" scoped>
@import "../../../assets/less/base.less";

.announcement-editor {
  color: @fontColor;
  min-height: 100%;
  background: white;
}
</style>

<style lang="less">
// Editor
.editor-container {
  height: 500px;

  .el-form-item__content {
    line-height: inherit;
    height: 100%;

    .quill-editor {
      height: 85%;
    }
  }
}
</style>
